package me.shiqiang.im.server;

import com.corundumstudio.socketio.AuthorizationListener;
import com.corundumstudio.socketio.HandshakeData;
import com.fasterxml.jackson.databind.JsonNode;
import me.shiqiang.im.utils.JsonUtils;
import me.shiqiang.im.utils.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by maliangxue on 2018/1/9.
 */
@Component
public class Auth implements AuthorizationListener {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    AuthService authService;

    @Override
    public boolean isAuthorized(HandshakeData handshakeData) {
        boolean result = false;
        try {
            logger.info("{}请求连接", handshakeData.getAddress().getAddress().getHostAddress());
            String ip = handshakeData.getAddress().getAddress().getHostAddress();
            if ("localhost".equals(ip) || "127.0.0.1".equals(ip)) {
                return true;
            }

            Map<String, List<String>> params = handshakeData.getUrlParams();

            String no = "sss";
            if (params.containsKey("no")) {
                no = params.get("no").get(0);
            }

            if (!params.containsKey("userId")) {
                logger.info("userId 不过");
                return result;
            }
            List<String> userIds = params.get("userId");
            if (!params.containsKey("sign")) {
                logger.info("sign 不过");
                return result;
            }
            List<String> signs = params.get("sign");
            if (!params.containsKey("ts")) {
                logger.info("ts 不过");
                return result;
            }
            List<String> tss = params.get("ts");
            if (!params.containsKey("deviceId")) {
                logger.info("deviceId不过");
                return result;
            }
            //todo 检查合法性
            List<String> deviceIds = params.get("deviceId");

            long userId = !userIds.isEmpty() ? Long.valueOf(userIds.get(0)) : 0;
            long ts = !tss.isEmpty() ? Long.valueOf(tss.get(0)) : 0;
            String sign = signs.isEmpty() ? "" : signs.get(0);
            String deviceId = deviceIds.isEmpty() ? "" : deviceIds.get(0);

            logger.info("{}校验参数：userId:{}，ts:{}，sign:{}，deviceId:{}",no, userId, ts, sign, deviceId);

            Date timestamp = new Date(ts);
            timestamp.setMinutes(5);
            if (timestamp.getTime() > System.currentTimeMillis()) {
                return result;
            }
            String resultStr = authService.getToken(userId, deviceId);
            JsonNode jsonNode = JsonUtils.getInstance().getMapper().readTree(resultStr);
            String token = jsonNode.get("res").textValue();
            logger.info("{},token: {}",no, token);
            logger.info("{} md5str:{}",no,userId + token + ts);
            String md5 = MD5Util.md5(userId + token + ts).toUpperCase();

            if (!md5.equals(sign)) {
                logger.info("{} md5不过，{}",no, md5);
                return result;
            }
            result = true;
        } catch (Exception e) {
            logger.error("校验异常", e);
            result = false;
        }
        return result;
    }
}
